package com.kcl.dfss.utils;

import java.sql.Date;
import java.sql.Time;
import java.util.ArrayList;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.kcl.dfss.utils.UsageRecordContract.RecordEntry;

public class ApplicationData {
	private String TAG = "ApplicationData";
	private Context mContext;
	private float mTotalTime = 0.0f;
	private static DatabaseUtils mDatabase;

	public static String app_version = "lite";
	
	private String[] mColumns = new String[] {
			RecordEntry.COLUMN_NAME_ENTRY_DATE,
			RecordEntry.COLUMN_NAME_ENTRY_START_TIME,
			RecordEntry.COLUMN_NAME_ENTRY_END_TIME,
			RecordEntry.COLUMN_NAME_ENTRY_DISTANCE,
			RecordEntry.COLUMN_NAME_ENTRY_AVESPEED };

	// private String mSelectionByDate =
	public ApplicationData(Context context) {
		mContext = context;
		mDatabase = new DatabaseUtils(mContext);
	}
	
	public ArrayList<UsageRecord> getUsageRecord(Date date) {
		Log.d(TAG,"getUsageRecord for date:"+date.toString());
		ArrayList<UsageRecord> list = new ArrayList<UsageRecord>();
		SQLiteDatabase database = mDatabase.getWritableDatabase();
		Cursor cursor = database.rawQuery("select * from records where date=?",
				new String[] { date.toString() });
		if (cursor != null && cursor.moveToFirst()) {
			do{
			list.add(new UsageRecord(cursor.getString(2), cursor.getString(3),
					cursor.getString(4), cursor.getFloat(5), cursor.getFloat(6)));
			}while(cursor.moveToNext());
		} 
		Log.d(TAG,"getUsageRecord get "+list.size()+" records"+" on "+date.toString());
		return list;
	}
	public float getTotalTime(){
		float totalTime = 0.0f;
		SQLiteDatabase database = mDatabase.getWritableDatabase();
		Cursor cursor = database.rawQuery("select * from records", null);
		if (cursor != null && cursor.moveToFirst()) {
			do{
			Time endTime = Time.valueOf(cursor.getString(4));
			Time startTime = Time.valueOf(cursor.getString(3));
			totalTime += (endTime.getTime()-startTime.getTime())/3600000.0f;
			}while(cursor.moveToNext());
		} 
		return totalTime;
	}
	public float getTotalMilage(){
		long totalmilage = 0;
		SQLiteDatabase database = mDatabase.getWritableDatabase();
		Cursor cursor = database.rawQuery("select * from records", null);
		if (cursor != null && cursor.moveToFirst()) {
			do{
			float milage = cursor.getFloat(5);
			totalmilage += milage;
			}while(cursor.moveToNext());
		} 
		return totalmilage;
	}
	public void insertUsageRecord(UsageRecord usage){
		SQLiteDatabase database = mDatabase.getWritableDatabase();
		long id = database.insert(UsageRecordContract.RecordEntry.TABLE_CONTENT, null, usage.getContentValues());
		if(id != -1){
			Log.e(TAG,"insert data "+usage.toString()+"  error!");
		}
	}
}
